import './UserManager.css'
import { Button, Form, Input, Modal, Space, Table, message, Select, Tag, Popconfirm } from 'antd'
import { useEffect, useState } from 'react'
import { addUser, deleteUser, getUserList, updateUser } from '../../api/user'
import { PlusOutlined, SearchOutlined, ReloadOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons'

export default function UserManager() {
    const [data, setData] = useState([])
    const [loading, setLoading] = useState(false)
    const [searchParams, setSearchParams] = useState({})
    const [isModalOpen, setIsModalOpen] = useState(false)
    const [currentUser, setCurrentUser] = useState(null)
    const [form] = Form.useForm()
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
    })

    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '账号',
            dataIndex: 'userAccount',
            key: 'userAccount',
        },
        {
            title: '昵称',
            dataIndex: 'userName',
            key: 'userName',
        },
        {
            title: '角色',
            dataIndex: 'userRole',
            key: 'userRole',
            render: (role) => (
                <Tag className={`user-role-tag ${role === 'admin' ? 'user-role-admin' : 'user-role-user'}`}>
                    {role === 'admin' ? '管理员' : '普通用户'}
                </Tag>
            ),
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button
                        type="primary"
                        size="small"
                        icon={<EditOutlined />}
                        onClick={() => showModal(record)}
                    >
                        编辑
                    </Button>
                    <Popconfirm
                        title="确认删除"
                        description="确定要删除这个用户吗？"
                        onConfirm={() => handleDelete(record.id)}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button
                            type="primary"
                            danger
                            size="small"
                            icon={<DeleteOutlined />}
                        >
                            删除
                        </Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ]

    const fetchData = async (params = {}) => {
        setLoading(true)
        try {
            const res = await getUserList({
                ...params,
                page: pagination.current,
                pageSize: pagination.pageSize,
            })
            setData(res.data.data.records || [])
            setPagination({
                ...pagination,
                total: res.data.total,
            })
        } catch (error) {
            message.error('获取用户列表失败')
        } finally {
            setLoading(false)
        }
    }

    const handleDelete = async (id) => {
        try {
            await deleteUser(id)
            message.success('删除成功')
            fetchData(searchParams)
        } catch (error) {
            message.error('删除失败')
        }
    }

    const handleSearch = (values) => {
        setSearchParams(values)
        fetchData(values)
    }

    const handleReset = () => {
        form.resetFields()
        setSearchParams({})
        fetchData()
    }

    const showModal = (user = null) => {
        setCurrentUser(user)
        form.setFieldsValue(user || {
            userAccount: '',
            userPassword: '',
            userName: '',
            userRole: 'user'
        })
        setIsModalOpen(true)
    }

    const handleOk = async () => {
        try {
            const values = await form.validateFields()
            if (currentUser) {
                await updateUser({ ...values, id: currentUser.id })
                message.success('更新成功')
            } else {
                await addUser(values)
                message.success('添加成功')
            }
            setIsModalOpen(false)
            fetchData(searchParams)
        } catch (error) {
            console.error('提交失败:', error)
        }
    }

    const handleCancel = () => {
        setIsModalOpen(false)
    }

    useEffect(() => {
        fetchData()
    }, [pagination.current])

    return (
        <div className="user-manager">
            {/* 页面标题 */}
            <div className="user-manager-header">
                <h1 className="user-manager-title">用户管理</h1>
                <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={() => showModal()}
                    size="large"
                >
                    添加用户
                </Button>
            </div>

            {/* 搜索栏 */}
            <div className="search-bar">
                <Form form={form} onFinish={handleSearch} className="search-form">
                    <Form.Item name="userAccount" label="账号">
                        <Input placeholder="请输入账号" />
                    </Form.Item>
                    <Form.Item name="userName" label="昵称">
                        <Input placeholder="请输入昵称" />
                    </Form.Item>
                    <Form.Item name="userRole" label="角色">
                        <Select placeholder="请选择角色" allowClear>
                            <Select.Option value="admin">管理员</Select.Option>
                            <Select.Option value="user">普通用户</Select.Option>
                        </Select>
                    </Form.Item>
                    <div className="search-buttons">
                        <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                            搜索
                        </Button>
                        <Button onClick={handleReset} icon={<ReloadOutlined />}>
                            重置
                        </Button>
                    </div>
                </Form>
            </div>

            {/* 用户表格 */}
            <div className="user-table-container">
                <Table
                    columns={columns}
                    dataSource={data}
                    rowKey="id"
                    loading={loading}
                    pagination={{
                        ...pagination,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total) => `共 ${total} 条记录`,
                        onChange: (page, pageSize) => {
                            setPagination({ ...pagination, current: page, pageSize })
                        },
                    }}
                />
            </div>

            {/* 用户编辑模态框 */}
            <Modal
                cancelText="取消"
                okText="确定"
                title={currentUser ? '编辑用户' : '添加用户'}
                open={isModalOpen}
                onOk={handleOk}
                onCancel={handleCancel}
                className="user-modal"
                width={600}
            >
                <Form form={form} layout="vertical">
                    <Form.Item
                        name="userAccount"
                        label="账号"
                        rules={[{ required: true, message: '请输入账号' }]}
                    >
                        <Input />
                    </Form.Item>
                    {!currentUser && (
                        <Form.Item
                            name="userPassword"
                            label="密码"
                            rules={[{ required: true, message: '请输入密码' }]}
                        >
                            <Input.Password />
                        </Form.Item>
                    )}
                    <Form.Item
                        name="userName"
                        label="昵称"
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="userRole"
                        label="角色"
                        rules={[{ required: true, message: '请选择角色' }]}
                    >
                        <Select placeholder="请选择角色">
                            <Select.Option value="user">普通用户</Select.Option>
                            <Select.Option value="admin">管理员</Select.Option>
                        </Select>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}